package net.fpeg.kotlin.msa.wordbase.service

import net.fpeg.kotlin.msa.wordbase.dao.WordNoteDao
import net.fpeg.kotlin.msa.wordbase.dto.WordNoteDto
import net.fpeg.kotlin.msa.wordbase.entity.WordNote
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class WordNoteService {
    @Autowired
    lateinit var wordNoteDao: WordNoteDao

    @Autowired
    lateinit var wordService: WordService

    @Autowired
    lateinit var wordUserService: WordUserService

    fun get(id: Long) = wordNoteDao.getById(id)
    fun get(uid: Long, wordValue: String) = wordNoteDao.getByWord_ValueAndWordUser_Id(wordValue, uid)
    fun getOne(uid: Long, wordValue: String) = get(uid, wordValue) ?: add(uid, wordValue)

    private fun add(uid: Long, wordValue: String) = wordNoteDao.save(
            WordNote(null, "", wordService.getOne(wordValue), wordUserService.getOne(uid))
    )

    fun edit(uid: Long, wordValue: String, wordNoteDto: WordNoteDto) =
            getOne(uid, wordValue).apply {
                value = wordNoteDto.wordNoteValue
            }.let { wordNoteDao.save(it) }
}